package edu.miami.group.photolog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;

import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CreatePhlog extends Activity {
	private static final int ACTIVITY_SELECT_PICTURE = 1;
	PhlogBase database;
	private boolean pictureSelected;
	Uri selectedURI;
	private long time;
	Bitmap selectedPicture;
	ContentValues databaseObject;
	boolean editMode;
	private Location location;
	double latitude, longitude;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create);
		
		pictureSelected = false;
		String tableName = getIntent().getStringExtra(Login.TABLE_NAME);
		database = new PhlogBase(this, tableName);
		//Gets the time
		time = System.currentTimeMillis();
		((TextView)findViewById(R.id.create_date)).setText((new Date(time)).toGMTString());
		//Checks to see if new entry or if getting an object from list
		editMode = false;
		databaseObject = this.getIntent().getParcelableExtra("databaseObject");
		if (databaseObject != null) {
			editMode = true;
			populateFields(databaseObject);
			Button button = (Button) findViewById(R.id.create_button);
			button.setText("Edit");
		} else {
			location = getLocation();
			try {
				latitude = location.getLatitude();
				longitude = location.getLongitude();
			} catch (Exception ex) {
				latitude = 0.0;
				longitude = 0.0;
			}
			TextView tv_location = (TextView) findViewById(R.id.create_location);
			tv_location.setText(ViewPhlog.formatLatLong(latitude, longitude));
		}
	}
	
	private Location getLocation()
	{
	    // Get the location manager
		LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
	    Criteria criteria = new Criteria ();
	    String bestProvider = locationManager.getBestProvider (criteria, false);
	    Location location = locationManager.getLastKnownLocation (bestProvider);

	    LocationListener loc_listener = new LocationListener() {
	        public void onLocationChanged(Location l) {
	        }

	        public void onProviderEnabled(String p) {
	        }

	        public void onProviderDisabled(String p) {
	        }

	        public void onStatusChanged(String p, int status, Bundle extras) {
	        }      
	    };
	    locationManager.requestLocationUpdates(bestProvider,0 ,0, loc_listener);
	    location = locationManager.getLastKnownLocation (bestProvider);
	    return location;
	}
	    
	private void populateFields(ContentValues fields) {
		TextView tv_date, tv_location;
		EditText et_description, et_title;
		ImageView iv_picture;
		
		// Find all the views
		et_title = (EditText) findViewById(R.id.create_title);
		tv_date = (TextView) findViewById(R.id.create_date);
		tv_location = (TextView) findViewById(R.id.create_location);
		et_description = (EditText) findViewById(R.id.create_description);
		iv_picture = (ImageView) findViewById(R.id.create_picture);
		
		// Set the easy ones first
		et_title.setText(databaseObject.getAsString("title"));
		et_description.setText(databaseObject.getAsString("description"));
		
		// Get, decode, and post the bitmap blob
		iv_picture.setImageBitmap(ViewPhlog.decodeBlob(databaseObject.getAsByteArray("picVid")));
		
		// Grab Lat / Long, format, and post
		double latitude = databaseObject.getAsDouble("latitude");
		double longitude = databaseObject.getAsDouble("longitude");
		tv_location.setText(ViewPhlog.formatLatLong(latitude, longitude));
		
		// Grab post date, format, and post
		String datetime = ViewPhlog.formatDate(databaseObject.getAsLong("date"));
		tv_date.setText(datetime);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_create_phlog, menu);
		return true;
	}

	private void openImageIntent() {

		// Determine Uri of camera image to save.
		final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
		root.mkdirs();
		final String fname = "temp";
		final File sdImageMainDirectory = new File(root, fname);
		selectedURI = Uri.fromFile(sdImageMainDirectory);

		// Camera.
		final List<Intent> cameraIntents = new ArrayList<Intent>();
		final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		final PackageManager packageManager = getPackageManager();
		final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
		for(ResolveInfo res : listCam) {
			final String packageName = res.activityInfo.packageName;
			final Intent intent = new Intent(captureIntent);
			intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
			intent.setPackage(packageName);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, selectedURI);
			cameraIntents.add(intent);
		}

		// Filesystem.
		final Intent galleryIntent = new Intent();
		galleryIntent.setType("image/*");
		galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

		// Chooser of filesystem options.
		final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");

		// Add the camera options.
		chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));

		startActivityForResult(chooserIntent, ACTIVITY_SELECT_PICTURE);
	}

	public void myClickListener(View view) {
		EditText et_title, et_description;

		switch (view.getId()){
		case R.id.create_picture:
			openImageIntent();
			break;
		//creates the entry by adding to the database
		case R.id.create_button:
			ContentValues newPhlogEntry;
			String toastMessage;
			
			et_title = (EditText) findViewById(R.id.create_title);
			et_description = (EditText) findViewById(R.id.create_description);
			
			if (editMode) {
				newPhlogEntry = databaseObject;
				newPhlogEntry.put("title", et_title.getText().toString());
				newPhlogEntry.put("description", et_description.getText().toString());
				newPhlogEntry.put("date", time);
				if (pictureSelected == true) {
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					selectedPicture.compress(Bitmap.CompressFormat.JPEG, 50, bos);
					byte[] bArray = bos.toByteArray();
					newPhlogEntry.put("picVid", bArray);
					
				}
				newPhlogEntry.put("_id", databaseObject.getAsInteger("_id"));
				database.updatePost(newPhlogEntry.getAsInteger("_id"), newPhlogEntry);
				editMode = false;
				Button button = (Button) findViewById(R.id.create_button);
				button.setText("Create");
				toastMessage = "Entry updated!";
			} else {
				if (pictureSelected == false) {
					Toast.makeText(this, "Please select a photo!", Toast.LENGTH_LONG).show();
					break;
				}
				newPhlogEntry = new ContentValues();
				newPhlogEntry.put("title", et_title.getText().toString());
				newPhlogEntry.put("description", et_description.getText().toString());
				newPhlogEntry.put("date", time);
				newPhlogEntry.put("latitude", latitude);
				newPhlogEntry.put("longitude", longitude);
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				selectedPicture.compress(Bitmap.CompressFormat.JPEG, 50, bos);
				byte[] bArray = bos.toByteArray();
				newPhlogEntry.put("picVid", bArray);
				database.addPost(newPhlogEntry);
				toastMessage = "New Entry Created!";
			}
			Toast.makeText(this, toastMessage, Toast.LENGTH_LONG).show();
			Intent returnIntent = new Intent();
			returnIntent.putExtra("databaseObject", newPhlogEntry);
			setResult(RESULT_OK,returnIntent);
			Recycler.recycleView(findViewById(R.id.create_picture));
			finish();
			break;

		default:
			break;
		}
	}
	
	@Override
	//onActivityResult for the picture selected
	public void onActivityResult(int requestCode,int resultCode,Intent data) {
		ImageView pictureView;

		super.onActivityResult(requestCode,resultCode,data);

		if(resultCode == RESULT_OK)
		{
			if(requestCode == ACTIVITY_SELECT_PICTURE)
			{
				final boolean isCamera;
				if(data == null)
				{
					isCamera = true;
				}
				else
				{
					final String action = data.getAction();
					if(action == null)
					{
						isCamera = false;
					}
					else
					{
						isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
					}
				}

				Uri selectedImageUri;
				if(isCamera)
				{
					selectedImageUri = selectedURI;
				}
				else
				{
					selectedImageUri = data == null ? null : data.getData();
				}
				selectedURI = selectedImageUri;
				pictureSelected = true;
				pictureView = (ImageView)findViewById(R.id.create_picture);
				try {
					selectedPicture = MediaStore.Images.Media.getBitmap(
							this.getContentResolver(),selectedURI);
					pictureView.setImageBitmap(selectedPicture);

				} catch (Exception e) {
					//----Should do something here                    
				}
			}
		}
	}

}
